package com.dao;

import com.beans.AdminInfo;
import com.beans.PageInfo;
import com.beans.RoleInfo;
import com.jdbc.DBUtil;
import sun.security.pkcs11.Secmod;

import java.util.List;

public class RoleDao {
    /**
     * 查询所有的角色列表
     * @return 列表
     */
    public List<RoleInfo> getRoleList(){
        return DBUtil.getList("select * from roleInfo order by id desc", RoleInfo.class);
    }

    /**
     * 根据角色id查询角色信息
     * @param roleId 角色id
     * @return 角色信息
     */
    public RoleInfo getRoleInfoById(int roleId) {
        return DBUtil.getSingleObj("select * from roleInfo where id=?", RoleInfo.class, roleId);
    }

    /**
     * 更新角色菜单信息
     * @param roleId 角色id
     * @param menuIdList 该角色的菜单列表
     */
    public void updateRoleMenu(int roleId, String[] menuIdList, String[] id) {
        //先删除这个角色原有的所有菜单
        DBUtil.update("delete from roleMenu where roleId=?", roleId);
        //再把新的菜单交给这个角色
        for(String menuId:menuIdList) {
            String sql="insert into roleMenu (roleID,menuId) values (?,?)";
            DBUtil.update(sql, roleId,menuId);
        }
        for(String t:id) {
            String sql="insert into roleMenu (roleID,menuId) values (?,?)";
            DBUtil.update(sql, roleId,t);
        }
    }

    /**
     * 查询某个角色有哪些菜单,以字符串的形式返回
     * @param roleId
     * @return
     */
    public String getMenuIdStr(int roleId) {
        String sql="select menuId from roleMenu where roleId=?" ;
        List<Integer> menuIdList= DBUtil.getColumn(sql, roleId);
        String str="";
        for(int i=0;i<menuIdList.size();i++) {
            if(i<menuIdList.size()-1) {
                str+=menuIdList.get(i)+",";
            }
            else {
                str+=menuIdList.get(i);
            }
        }

        return str;
    }

    public RoleInfo getRoleInfoByName(String name) {
        return DBUtil.getSingleObj("select * from roleinfo where rolename=?",RoleInfo.class,name);
    }

    public int addroleinfo(RoleInfo roleInfo) {
        return DBUtil.addAndReturnId("insert into roleinfo (rolename,des) values(?,?)",roleInfo.getRoleName(),roleInfo.getDes());
    }

    public int updaterole(RoleInfo roleInfo) {
        return DBUtil.update("update roleinfo set rolename=?,des=? where id=?",roleInfo.getRoleName(),roleInfo.getDes(),roleInfo.getId());
    }

    public int delete(int id) {
        return DBUtil.update("delete from roleinfo where id=?",id);
    }

    public List<AdminInfo> getAdminList(PageInfo page) {
        return  DBUtil.getList("select a.id,a.adminName,a.state,a.editDate,b.roleName from adminInfo a left join roleInfo b on a.roleId=b.id limit ?,?",
                AdminInfo.class,page.getBeginRow(),page.getPageSize());
    }

    public int update(String rolename, int id) {
        return DBUtil.update("update admininfo set roleid=? where adminname=?",id,rolename);
    }
}
